package com.xinyue.auto.reader.major;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import com.xinyue.auto.annotation.ListClear;
import com.xinyue.auto.bean.Attribute;
import com.xinyue.auto.bean.Query;
import com.xinyue.auto.exception.JoinException;
import com.xinyue.auto.reader.Process;
import com.xinyue.auto.reader.ProcessContext;
import com.xinyue.auto.util.StringUtil;

public abstract class JoinMajor extends ProcessContext{
	public JoinMajor(Process read) {
		super(read);
	}
	@ListClear
	protected List<Query> querys = new ArrayList<Query>();//查询方法
	@ListClear
	protected List<Attribute> atts = new ArrayList<Attribute>();//属性集合
	protected String entity;//实体名称
	protected Attribute att;//属性实体对象
	
	/**
	 * 读取fand标签下的query、hql、sql标签的共有属性
	 * @param find
	 * @return
	 * @throws Exception
	 */
	protected void commonRead(Element join) throws Exception {
		entity = join.attributeValue(entity_);
		String key = join.attributeValue(join_key_);
		String type = null;
		String tName = null;
		String len = null;
		
		//空数据验证
		if(StringUtil.isNull(entity)) {
			throw new JoinException("entity属性未定义或其值为空", holder.getException());
		}
		if(StringUtil.isNull(key)) {
			throw new JoinException("join-key属性未定义或其值为空", holder.getException());
		}
		
		//数据合法性验证
		Node n = xml.selectSingleNode("/build-mapping/entity[@name='" + entity + "']");
		if(n == null) {
			throw new JoinException("entity属性值非法：" + entity, holder.getException());
		}else {
			Node nk = n.selectSingleNode("id[@name='" + key + "']");
			if(nk == null) {
				nk = n.selectSingleNode("property[@name='" + key + "']");
			}
			if(nk == null) {
				throw new JoinException("join-key属性值非法：" + key, holder.getException());
			}
			
			//验证通过则setter数据
			type = nk.valueOf("@type");
			tName = nk.valueOf("@t_name");
			len = nk.valueOf("@length");
		}
		
		String column = "";//注解信息
		att = new Attribute();
		att.setName(key);
		att.setType(type);
		att.setDbField(true);
		
		if(!StringUtil.isNull(tName)) {
			att.setDbName(tName);
			column += ", " + "name = \"" + tName + "\"";
		}
		if(!StringUtil.isNull(len)) {
			att.setLength(len);
			column += ", " + "length = " + len;
		}
		
		if(column.length() > 0) {
			String[] ann = {"@Column(" + column.substring(2, column.length()) + ")"};
			holder.getBeanImpt().add("javax.persistence.Column");
			att.setAnnotations(ann);
		}
	}
}